<?php


namespace App\Services;


use App\Models\HelpDoc;
use Illuminate\Database\Eloquent\Model;

class HelpDocService
{
    /**
     * 保存左侧标题树
     *
     * @param $clickNodeId
     * @param $title
     * @return bool
     * @author: lxk
     * @date: 2025-03-29 15:20
     */
    public function saveTitle($clickNodeId, $title) : bool
    {
        if (is_numeric($clickNodeId)) { //新增
            $helpDoc = new HelpDoc();
            $helpDoc->menu_id = $clickNodeId;
        } else {
            $id = self::getTitleId($clickNodeId);
            $helpDoc = HelpDoc::query()->find($id);
        }
        $helpDoc->title = $title;

        return $helpDoc->save();
    }

    /**
     *
     *
     * @return array
     * @author: lxk
     * @date: 2025-04-01 13:08
     */
    public function getTitleTree() : array
    {
        $ruleMenus = RuleMenuService::getMenuArray();
        $ruleMenus = (new RuleMenuService())->getTree($ruleMenus);
        foreach ($ruleMenus as &$val) {
            $val['is_have_children'] = 0;
            if (isset($val['children'])) { //就是说这里只要一级菜单
                unset($val['children']);
            }
            $list = HelpDoc::query()->where('menu_id', $val['id'])->select('id', 'menu_id', 'title', 'sort')->get();
            if ($list->isNotEmpty()) {
                $children = $list->toArray();
                foreach ($children as &$val2) {
                    $val2['id'] = $val['id'] . '_' . $val2['id'];
                }
                $val['children']         = $children;
                $val['is_have_children'] = 1;
            }
        }

        return $ruleMenus;
    }

    /**
     * 获取 help_doc 主键 id
     *
     * @param $clickNodeId
     * @return string
     * @author: lxk
     * @date: 2025-04-01 15:57
     */
    public static function getTitleId($clickNodeId) : string
    {
        return  substr($clickNodeId, strpos($clickNodeId, '_') + 1);
    }



    public function getMenuIds($menus)
    {
        $menuIds = [];
        foreach ($menus as $menu) {
            $menuIds[] = $menu;
            if (isset($menu['children'])) {
                $menuIds = array_merge($menuIds, $this->getMenuIds($menu['children']));
            }
        }

        return $menuIds;
    }


}
